$("#mfile").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/khexcel?type=khexcel',
    allowedFileExtensions: ["xlsx", "xls"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $('#path').val(data.response.data)
})

function hytypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else return ""
}

function shengChange(code,shengsel, shisel,area) {

    $("#"+area).val($("#"+shengsel).find("option:selected").text())

    $.ajax({
        type: 'get',
        url: "/admin/area/shi",
        data: {
            code: code,
            isempty: 1
        },
        success: function (d) {
            $("#"+shisel).empty()
            console.log(d)
            $.each(d.info,function(idx,item){
                console.log(item)
                $("#"+shisel).append("<option value='"+item.code+"'>"+item.name+"</option>");
            })
        },
        dataType: "json"
    });
}
function shiChange(shisel,shi) {
    console.log($("#"+shisel).find("option:selected").text())
    $("#"+shi).val($("#"+shisel).find("option:selected").text())
    console.log($("#"+shi).val())
}
function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/kehu/list'});
        },
        dataType: "json"
    });
}
function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/kehu/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function add() {
    checkAdd()
    $.ajax({
        type: 'POST',
        url: "add",
        data: $('#aform').serialize(),
        success: function (data) {
            swal({title: "修改成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh', {url: '/admin/kehu/list'});
            $('#modal-add-form').modal('hide');
        },
        dataType: "json"
    });
}

function modify() {
    checkModify()
    var opts = $('#mytable').bootstrapTable('getOptions').queryParams
    console.log("=====================modify opts")
    console.log(opts)
    $.ajax({
        type: 'POST',
        url: "modify",
        data: $('#mform').serialize(),
        success: function (data) {
            swal({title: "修改成功", text: "", type: "success"})
            // $('#mytable').bootstrapTable('refresh', {url: '/admin/kehu/list'});
            $('#mytable').bootstrapTable('refresh', opts);
            $('#modal-form').modal('hide');
        },
        dataType: "json"
    });
}

function saveaddfile() {

    if($("#hyname3").val().length==0){
        swal({title: "请填写行业类别", text: "", type: "error"})
        return;
    }
    if($("#path").val().length==0){
        swal({title: "请上传excel文件", text: "", type: "error"})
        return;
    }
    $.ajax({
        type: 'POST',
        url: "addfile",
        data: $('#fform').serialize(),
        success: function (data) {
            swal({title: "修改成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh', {url: '/admin/kehu/list'});
            $('#modal-add-file').modal('hide');
        },
        dataType: "json"
    });
}
var editsw = [];

/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)

    modal.find('#id').val(data.id)
    modal.find('#name').val(data.name)
    modal.find('#mname').val(data.mname)
    modal.find('#hyname').val(data.hyname)
    // modal.find('#hytype').find("option[value='" + data['hytype'] + "']").attr("selected", true);
    modal.find('#areacode').find("option[value='" + data['areacode'] + "']").attr("selected", true);

    $.ajax({
        type: 'get',
        url: "/admin/area/shi",
        data: {
            code: data['areacode'],
            isempty: 1
        },
        success: function (d) {
            $("#shicode").empty()
            $.each(d.info,function(idx,item){
                console.log(item)
                if(data['shicode']==item.code)
                    $("#shicode").append("<option value='"+item.code+"' selected>"+item.name+"</option>");
                else
                    $("#shicode").append("<option value='"+item.code+"'>"+item.name+"</option>");
            })
        },
        dataType: "json"
    });

    modal.find('#area').val(data.area)
    modal.find('#shi').val(data.shi)

    modal.find('#hyname').val(data.hyname)
    modal.find('#phone').val(data.phone)
    modal.find('#telephone').val(data.telephone)
    modal.find('#remark').val(data.remark)

    modal.find('#address').val(data.address)
    modal.find('#longitude').val(data.longitude)
    modal.find('#latitude').val(data.latitude)
    modal.find('#email').val(data.email)
    modal.find('#website').val(data.website)
    editsw["isWxuser"] == undefined ? editsw["isWxuser"] = new Switchery(document.querySelector('#isWxuser'), {color: "#1AB394"}) : ""
    if (data.isWxuser == 1) {
        setSwitchery(editsw["isWxuser"], true);
    } else {
        setSwitchery(editsw["isWxuser"], false);
    }
    editsw["state"] == undefined ? editsw["state"] = new Switchery(document.querySelector('#state'), {color: "#1AB394"}) : ""
    if (data.state == 1) {
        setSwitchery(editsw["state"], true);
    } else {
        setSwitchery(editsw["state"], false);
    }
})
function actionFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var res = '<button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    // if (state == undefined) {
    // } else if (state == 1)
    //     res += ' <button type="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',-1)" >禁用</button>';
    // else
    //     res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',1)" >启用</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">删除</button>';
    return res;
}
//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

$(function () {
    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })
    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/kehu/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 20,//单页记录数
        pageList: [20,40, 80, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '商家名',
                field: 'mname'
            },
            {
                title: '联系人',
                width:70,
                field: 'name'
            },
            {
                title: '行业类型',
                width:60,
                field: 'hyname'
            },
            {
                title: '手机号',
                width:80,
                field: 'phone'
            },
            {
                title: '座机号',
                width:80,
                field: 'telephone'
            },
            // {
            //     title: '省市',
            //     width:80,
            //     field: 'area'
            // },
            {
                title: '市区',
                width:80,
                field: 'shi'
            },
            {
                title: '地址',
                field: 'address'
            },
            {
                title: '邮箱',
                width:120,
                field: 'email'
            },
            {
                title: '备注',
                width:200,
                field: 'remark'
            },
            {
                title: '客户经理',
                field: 'modifyname'
            },
            {
                title: '是否微信用户',
                field: 'isWxuser',
                formatter: "sfFormatter"
            },
            // {
            //     title: '启用状态',
            //     field: 'state',
            //     formatter: "stateFormatter"
            // },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 170,
                formatter: actionFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    })

    //请求服务数据时所传参数
    function queryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order
            , search: $('#search').val() || ""
            , sheng: $('#pshengcode').val() || ""
            , shi: $('#pshicode').val() || ""
        }
        return p;
    }

    $('#search_btn').click(function () {
        var p = {
            status: $('#qstatus').val(),
            search: $('#search').val(),
            ts: new Date().getTime()
        };
        $('#mytable').bootstrapTable('refresh', p);
    })

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });

    return true;
}

function checkModify() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });

    return true;
}